import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
data_file = 'http://lib.stat.cmu.edu/datasets/boston'
raw_df = pd.read_csv(data_file, sep='\\s+', header=None, skiprows=22)
raw_array = raw_df.values
x = np.hstack([raw_array[::2, :], raw_array[1::2, :2]])
y = raw_array[1::2, 2]
print(f"特征矩阵形状: {x.shape}")
print(f"目标变量形状: {y.shape}")
x_train, x_test, y_train, y_test = train_test_split(
    x, y, test_size=0.2, random_state=42
)
model = LinearRegression()
model.fit(x_train, y_train)
y_pred = model.predict(x_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("\n线性回归模型评估：")
print(f"均方误差（MSE）: {mse:.2f}")
print(f"决定系数（R²）: {r2:.2f}")
print(f"模型系数（各特征权重）: {model.coef_}")
print(f"模型截距: {model.intercept_:.2f}")
